import pymysql
#  TODO 数据库操作模块
#  TODO 封装一个数据库操作类DB
#  TODO 读方法read(sql) return 受影响行数 结果集
#  TODO 写方法write(sql) return 受影响行数
class DB:                   #定义一个DB类
    def __init__(self, database, host='localhost', user='user', password='root', port=3306, charset='utf8',
                 cursor_type=pymysql.cursors.Cursor):
        self.__conn = pymysql.connect(host=host, user=user, password=password, port=port, charset=charset,
                                    database=database)
        # 游标类型: 元组 字典
        self.__cursor = self.conn.cursor(cursor_type)
    # 设置读方法
    def read(self, sql, params_list=[]):
        try:
            rows = self.__cursor.execute(sql, params_list)
            data = self.__cursor.fetchall()
        except Exception as e:
            print('sql语法输入有误')
            return None, 'NO data'
        return rows, data
    # 设置写方法
    def write(self, sql):
        try:
            rows = self.__cursor.execute(sql)
        except Exception as e:
            self.__conn.rollback()          # 回滚
        else:
            self.__conn.commit()            # 提交
        return rows
    def __del__(self):
        self.__cursor.close()
        self.__conn.close()




